package cn.tx.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtil {

    static String username=null;
    static  String password=null;
    static  String url=null;
    static  String driver=null;

    static{

        InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            properties.load(in);
            driver=properties.getProperty("driver");
            url=properties.getProperty("url");
            username=properties.getProperty("uname");
            password=properties.getProperty("pword");


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    //封装了获得连接

    public static Connection getConn(){
        Connection connection=null;

        try {
            Class.forName(driver);
            connection= DriverManager.getConnection(url,username,password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return connection;

    }

    public  static PreparedStatement getPrepareStatement(String sql){

        Connection conn=getConn();
        PreparedStatement ps=null;

        try {
            ps=conn.prepareStatement(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ps;

    }

    public static  void closeRes(Statement statement){

        if(statement!=null){

            try {
                Connection connection = statement.getConnection();
                statement.close();
                if(connection!=null){
                    connection.close();
                }

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static  void closeRes(ResultSet rs){
        try {
            if(rs!=null){
                Statement statement = rs.getStatement();
                rs.close();

                if(statement!=null){

                    try {
                        Connection connection = statement.getConnection();
                        statement.close();
                        if(connection!=null){
                            connection.close();
                        }

                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }
}
